﻿using System;
using System.Runtime.InteropServices;
using UnityEngine;

[Serializable, StructLayout(LayoutKind.Sequential)]
public struct NetworkDirection
{
    public byte angle;
    public NetworkDirection(byte angle)
    {
        this.angle = angle;
    }

    private static float Angle(Vector3 vector)
    {
        if (vector.x < 0f)
        {
            return (360f - ((Mathf.Atan2(vector.x, vector.z) * 57.29578f) * -1f));
        }
        return (Mathf.Atan2(vector.x, vector.z) * 57.29578f);
    }

    public override string ToString()
    {
        return string.Format("({0})", this.angle);
    }

    public static implicit operator Vector3(NetworkDirection v)
    {
        if (v.angle == 0)
        {
            return Vector3.zero;
        }
        return (Vector3) (Quaternion.Euler(0f, (((float) (v.angle + 1)) / 256f) * 360f, 0f) * Vector3.forward);
    }

    public static implicit operator NetworkDirection(Vector3 v)
    {
        if (v == Vector3.zero)
        {
            return new NetworkDirection(0);
        }
        return new NetworkDirection((byte) (((Angle(v) / 360f) * 256f) + 1f));
    }
}

